// api/procurement.ts
import http from './http'
import { getCachedData, clearCache } from '@/utils/cache'
import { requestWithRetry } from '@/utils/retry'

// 进货入库相关API

// 获取入库单列表
export const getInboundOrders = async (params: any) => {
  try {
    const data: any = await http.get('/procurement/inbound-orders', { params });
    return {
      success: true,
      data: {
        list: data.list || [],
        pagination: data.pagination || {
          page: 1,
          limit: 20,
          total: 0
        }
      }
    };
  } catch (error: any) {
    return {
      success: false,
      data: {
        list: [],
        pagination: null
      },
      message: error.message || '获取入库单列表失败'
    };
  }
}

// 获取入库单详情
export const getInboundOrderDetail = async (id: number) => {
  try {
    const data = await http.get(`/procurement/inbound-orders/${id}`);
    return {
      success: true,
      data: data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '获取入库单详情失败'
    };
  }
};

// 创建入库单
export const createInboundOrder = async (data: any) => {
  try {
    const result = await http.post('/procurement/inbound-orders', data);
    // 清除相关缓存
    clearCache('suppliers');
    clearCache('products');
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '创建入库单失败'
    };
  }
}

// 更新入库单
export const updateInboundOrder = async (id: number, data: any) => {
  try {
    const result = await http.put(`/procurement/inbound-orders/${id}`, data);
    // 清除相关缓存
    clearCache('suppliers');
    clearCache('products');
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '更新入库单失败'
    };
  }
};

// 删除入库单
export const deleteInboundOrder = async (id: number) => {
  try {
    const result = await http.delete(`/procurement/inbound-orders/${id}`);
    // 清除相关缓存
    clearCache('suppliers');
    clearCache('products');
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '删除入库单失败'
    };
  }
}

// 供应商相关API

// 获取供应商列表
export interface Supplier {
  id: number
  name: string
  contactPerson: string | null
  phone: string
  email: string
  address: string
  remark: string
  status: string
  rating: string | number
  cooperationDate?: string
  createdAt: string
  updatedAt: string
}

export interface SupplierQueryParams {
  name?: string
  contactPerson?: string
  phone?: string
  email?: string
  status?: string
  createdAtStart?: string
  createdAtEnd?: string
  page: number
  limit: number
}

export interface SupplierListResponse {
  success: boolean
  data: {
    list: Supplier[]
    pagination: {
      page: number
      limit: number
      total: number
    }
    stats: {
      total: number
      active: number
      pending: number
    }
  }
  message?: string
}

export const getSuppliers = async (params: SupplierQueryParams) => {
  try {
    // 使用缓存机制获取供应商列表
    const result: any = await getCachedData(
      'suppliers', 
      async () => {
        const response = await http.get('/procurement/suppliers', { params });
        return response.data; // 返回实际的数据而不是整个响应对象
      },
      5 * 60 * 1000 // 5分钟缓存
    );
    
    if (result.success && result.data) {
      return {
        success: true,
        data: {
          list: result.data.list || [],
          pagination: result.data.pagination || {
            page: 1,
            limit: 20,
            total: 0
          },
          stats: result.data.stats || {
            total: 0,
            active: 0,
            pending: 0
          }
        }
      }
    } else {
      return {
        success: false,
        data: {
          list: [],
          pagination: {
            page: 1,
            limit: 20,
            total: 0
          },
          stats: {
            total: 0,
            active: 0,
            pending: 0
          }
        },
        message: result.message || '获取供应商列表失败'
      }
    }
  } catch (error: any) {
    return {
      success: false,
      data: {
        list: [],
        pagination: {
          page: 1,
          limit: 20,
          total: 0
        },
        stats: {
          total: 0,
          active: 0,
          pending: 0
        }
      },
      message: error.message || '获取供应商列表失败'
    }
  }
}

// 获取供应商详情
export const getSupplierDetail = async (id: number) => {
  try {
    const data = await http.get(`/procurement/suppliers/${id}`)
    return {
      success: true,
      data: data
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '获取供应商详情失败'
    }
  }
}

// 创建供应商
export const createSupplier = async (data: Omit<Supplier, 'id' | 'createdAt' | 'updatedAt'>) => {
  try {
    const result = await http.post('/procurement/suppliers', data)
    // 清除供应商缓存
    clearCache('suppliers');
    return {
      success: true,
      data: result
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '创建供应商失败'
    }
  }
}

// 更新供应商
export const updateSupplier = async (id: number, data: Partial<Supplier>) => {
  try {
    const result = await http.put(`/procurement/suppliers/${id}`, data)
    // 清除供应商缓存
    clearCache('suppliers');
    return {
      success: true,
      data: result
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '更新供应商失败'
    }
  }
}

// 激活供应商
export const activateSupplier = async (id: number) => {
  try {
    const result = await http.put(`/procurement/suppliers/${id}`, { status: 'active' })
    // 清除供应商缓存
    clearCache('suppliers');
    return {
      success: true,
      data: result
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '激活供应商失败'
    }
  }
}

// 停用供应商
export const deactivateSupplier = async (id: number) => {
  try {
    const result = await http.put(`/procurement/suppliers/${id}`, { status: 'suspended' })
    // 清除供应商缓存
    clearCache('suppliers');
    return {
      success: true,
      data: result
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '停用供应商失败'
    }
  }
}

// 删除供应商
export const deleteSupplier = async (id: number) => {
  try {
    const result = await http.delete(`/procurement/suppliers/${id}`)
    // 清除供应商缓存
    clearCache('suppliers');
    return {
      success: true,
      data: result
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '删除供应商失败'
    }
  }
}

// 批量删除供应商
export const batchDeleteSuppliers = async (ids: number[]) => {
  try {
    const result = await http.post('/procurement/suppliers/batch-delete', { ids })
    // 清除供应商缓存
    clearCache('suppliers');
    return {
      success: true,
      data: result
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '批量删除供应商失败'
    }
  }
}

// 批量激活供应商
export const batchActivateSuppliers = async (ids: number[]) => {
  try {
    const result = await http.post('/procurement/suppliers/batch-activate', { ids })
    // 清除供应商缓存
    clearCache('suppliers');
    return {
      success: true,
      data: result
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '批量激活供应商失败'
    }
  }
}

// 批量停用供应商
export const batchDeactivateSuppliers = async (ids: number[]) => {
  try {
    const result = await http.post('/procurement/suppliers/batch-deactivate', { ids })
    // 清除供应商缓存
    clearCache('suppliers');
    return {
      success: true,
      data: result
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '批量停用供应商失败'
    }
  }
}

// 导出供应商
export const exportSuppliers = async (params: any) => {
  try {
    const response = await http.get('/procurement/suppliers/export', { 
      params,
      responseType: 'blob'
    })
    return {
      success: true,
      data: response.data
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '导出供应商失败'
    }
  }
}

// 导出供应商模板
export const exportSupplierTemplate = async () => {
  try {
    const response = await http.get('/procurement/suppliers/export-template', {
      responseType: 'blob'
    })
    return {
      success: true,
      data: response.data
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '导出供应商模板失败'
    }
  }
}

// 导入供应商
export const importSuppliers = async (file: File, fieldMapping?: Record<string, string>) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    // 如果有字段映射关系，也一并传递
    if (fieldMapping) {
      formData.append('fieldMapping', JSON.stringify(fieldMapping))
    }
    
    const response = await http.post('/procurement/suppliers/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 60000 // 为导入请求设置60秒超时
    })
    
    // 统一导入结果结构
    const result = response.data || response;
    // 清除供应商缓存
    clearCache('suppliers');
    return {
      success: true,
      data: {
        importedCount: result.importedCount || 0,
        errorCount: result.errorCount || 0,
        errors: result.errors || []
      }
    }
  } catch (error: any) {
    return {
      success: false,
      data: {
        importedCount: 0,
        errorCount: 0,
        errors: []
      },
      message: error.message || '导入供应商失败'
    }
  }
}

// 获取供应商统计信息
export const getSupplierStats = async () => {
  try {
    // 使用缓存机制获取供应商统计信息
    const result: any = await getCachedData(
      'supplierStats', 
      async () => {
        const response = await http.get('/procurement/suppliers/stats');
        return response.data; // 返回实际的数据而不是整个响应对象
      },
      5 * 60 * 1000 // 5分钟缓存
    );
    
    if (result.success) {
      return {
        success: true,
        data: {
          total: result.data?.total || 0,
          active: result.data?.status?.active || 0,
          pending: result.data?.status?.pending || 0,
          suspended: result.data?.status?.suspended || 0,
          terminated: result.data?.status?.terminated || 0,
          recent: result.data?.recent || 0,
          risk: result.data?.risk || 0
        }
      }
    } else {
      return {
        success: false,
        data: null,
        message: result.message || '获取供应商统计信息失败'
      }
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '获取供应商统计信息失败'
    }
  }
}

// 获取商品列表
export const getProducts = async (params: any) => {
  try {
    const response = await http.get('/inventory/products', { params });
    const data = response.data || response;
    return {
      success: true,
      data: {
        list: Array.isArray(data) ? data : (data.list || data || []),
        pagination: null
      }
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '获取商品列表失败'
    };
  }
};

// 导出入库单
export const exportInboundOrders = async (params: any) => {
  try {
    const response = await http.get('/procurement/inbound-orders/export', { 
      params,
      responseType: 'blob'
    });
    return {
      success: true,
      data: response.data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '导出入库单失败'
    };
  }
}

// 导出入库单模板
export const exportInboundOrderTemplate = async () => {
  try {
    const response = await http.get('/procurement/inbound-orders/export-template', {
      responseType: 'blob'
    });
    return {
      success: true,
      data: response.data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '导出入库单模板失败'
    };
  }
}

// 导入入库单
export const importInboundOrders = async (formData: FormData) => {
  try {
    const response = await http.post('/procurement/inbound-orders/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    // 清除相关缓存
    clearCache('suppliers');
    clearCache('products');
    return {
      success: true,
      data: response.data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '导入入库单失败'
    };
  }
}

// 获取统计信息
export const getInboundStats = async () => {
  try {
    const response = await http.get('/procurement/inbound-orders/stats');
    const data = response.data || response;
    return {
      success: true,
      data: data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '获取统计信息失败'
    };
  }
}

// 采购订单相关API

// 获取采购订单列表
export const getPurchaseOrders = async (params: any) => {
  try {
    // 使用重试机制获取采购订单列表
    const response: any = await requestWithRetry(
      () => http.get('/procurement/purchase-orders', { params }),
      3, // 最多重试3次
      1000 // 基础延迟1秒
    );
    
    return {
      success: true,
      data: {
        list: response.data?.list || [],
        pagination: response.data?.pagination || {
          page: 1,
          limit: 20,
          total: 0
        }
      }
    }
  } catch (error: any) {
    return {
      success: false,
      data: {
        list: [],
        pagination: null
      },
      message: error.message || '获取采购订单列表失败'
    }
  }
}

// 获取采购订单详情
export const getPurchaseOrderDetail = async (id: number) => {
  try {
    // 使用重试机制获取采购订单详情
    const response = await requestWithRetry(
      () => http.get(`/procurement/purchase-orders/${id}`),
      3, // 最多重试3次
      1000 // 基础延迟1秒
    );
    
    return {
      success: true,
      data: response.data
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '获取采购订单详情失败'
    }
  }
}

// 创建采购订单
export const createPurchaseOrder = async (data: any) => {
  try {
    const result = await http.post('/procurement/purchase-orders', data)
    // 清除采购订单缓存
    clearCache('purchaseOrders');
    return {
      success: true,
      data: result
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '创建采购订单失败'
    }
  }
}

// 更新采购订单
export const updatePurchaseOrder = async (id: number, data: any) => {
  try {
    const result = await http.put(`/procurement/purchase-orders/${id}`, data)
    // 清除采购订单缓存
    clearCache('purchaseOrders');
    return {
      success: true,
      data: result
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '更新采购订单失败'
    }
  }
}

// 删除采购订单
export const deletePurchaseOrder = async (id: number) => {
  try {
    const result = await http.delete(`/procurement/purchase-orders/${id}`)
    // 清除采购订单缓存
    clearCache('purchaseOrders');
    return {
      success: true,
      data: result
    }
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '删除采购订单失败'
    }
  }
}

// 获取采购订单统计信息
export const getPurchaseOrderStats = async () => {
  try {
    // 使用缓存机制获取采购订单统计信息
    const result: any = await getCachedData(
      'purchaseOrderStats', 
      async () => {
        const response = await http.get('/procurement/purchase-orders/stats');
        return response.data; // 返回实际的数据而不是整个响应对象
      },
      5 * 60 * 1000 // 5分钟缓存
    );
    
    if (result.success && result.data) {
      return {
        success: true,
        data: {
          totalOrders: result.data.totalOrders || 0,
          pendingOrders: result.data.pendingOrders || 0,
          completedOrders: result.data.completedOrders || 0,
          monthlyAmount: result.data.monthlyAmount || 0,
          supplierCount: result.data.supplierCount || 0
        }
      };
    } else {
      return {
        success: false,
        data: {
          totalOrders: 0,
          pendingOrders: 0,
          completedOrders: 0,
          monthlyAmount: 0,
          supplierCount: 0
        },
        message: result.message || '获取采购订单统计信息失败'
      };
    }
  } catch (error: any) {
    return {
      success: false,
      data: {
        totalOrders: 0,
        pendingOrders: 0,
        completedOrders: 0,
        monthlyAmount: 0,
        supplierCount: 0
      },
      message: error.message || '获取采购订单统计信息失败'
    };
  }
}
